{% load static %}
<div id="id_{{ name }}_wrapper" style="display: inline-block; width: 250px;">
    <div class="flex-item" style="flex: 1">
        <input name="{{ raw_name }}" type="hidden" v-model="inputValue">
        <el-cascader
                clearable
                :options="options"
                v-model="value"
                :props="{ checkStrictly: strictly}"
                @change="onChange">

        </el-cascader>
    </div>
</div>
<style>
    #id_{{ name }}_wrapper {
        display: flex;
        justify-content: space-between;
    }

    .flex-item {
        display: inline-block;
    {#align-items: center;#}
    }
</style>
<script type="text/javascript">
    //需要隐藏当前的id，防止死循环

    new Vue({
        el: '#id_{{ name }}_wrapper',
        data: {
            value: '{{ value }}',
            options:{{ options|safe }},
            visible: false,
            strictly: '{{ strictly|safe }}' === 'True',

        },
        computed:{
            inputValue(){
                let val=this.value;
                //如果val存在并且是个数组的时候，取数组最后一项
                if(val && val.length>0){
                    return val[val.length-1];
                }
                return this.value;
            }
        },
        created() {
            this.convert();
        },
        methods: {
            deepFind(data, value) {
                // 递归查找，获取value的所有父级id
                let result = []
                for (let i = 0; i < data.length; i++) {
                    if (data[i].value.toString() === value.toString()) {
                        result.push(data[i].value)
                        return result
                    } else if (data[i].children) {
                        let temp = this.deepFind(data[i].children, value)
                        if (temp.length > 0) {
                            result.push(data[i].value)
                            return result.concat(temp)
                        }
                    }
                }
                return result
            },
            convert() {
                let self = this;
                // 将value转换为数组
                let val = self.value;
                self.value = self.deepFind(self.options, val);
            },
            onChange(value) {
                console.log(value);
                if (value.length > 0) {
                    this.value = value[value.length - 1];
                } else {
                    this.value = '';
                }
            }
        }
    });

</script>
